package com.andaily.domain.thing.handler;

import com.andaily.domain.dto.thing.ThingDto;
import com.andaily.domain.shared.DateUtils;
import com.andaily.domain.thing.Thing;
import com.andaily.domain.thing.ThingPriority;
import com.andaily.domain.thing.ThingStatus;
import com.andaily.infrastructure.support.st.STRender;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date: 13-7-25
 *
 * @author Shengzhao Li
 */
public class AutoStartThingMailRender {

    public static final String TEMPLATE = "template/auto_start_thing.html";
    public static final String ITEM_TEMPLATE = "template/auto_start_thing_item.html";

    private final String subject;
    private final Date startDate;
    private final List<Thing> things;

    public AutoStartThingMailRender(String subject, Date startDate, List<Thing> things) {
        this.subject = subject;
        this.startDate = startDate;
        this.things = things;
    }

    public String render() {
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("title", subject);
        attributes.put("date", DateUtils.toDateText(startDate));
        attributes.put("thingContent", generateThingContent());

        STRender stRender = new STRender(TEMPLATE, attributes);
        return stRender.render();
    }

    private String generateThingContent() {
        StringBuilder sb = new StringBuilder();
        STRender stRender = new STRender(ITEM_TEMPLATE);
        Map<String, Object> attributes = new HashMap<String, Object>();

        int index = 0;
        for (Thing thing : things) {
            index = itemAttributes(attributes, index, thing);
            String render = stRender.render(attributes);
            sb.append(render);
        }
        return sb.toString();
    }

    private int itemAttributes(Map<String, Object> attributes, int index, Thing thing) {
        attributes.clear();
        attributes.put("thing", new ThingDto(thing));
        attributes.put("ntr", (index++ % 2 == 0));
        attributes.put("priorityStyle", priorityStyle(thing.priority()));
        attributes.put("status", ThingStatus.PENDING);     // all thing is pending now
        return index;
    }

    //see auto_start_thing.html file css style definition
    private String priorityStyle(ThingPriority priority) {
        switch (priority) {
            case HIGH:
                return "priority-high";
            case HIGHER:
                return "priority-higher";
            case LOW:
                return "priority-low";
            case LOWER:
                return "priority-lower";
        }
        return "";
    }
}
